const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}

const nowTimeString = function() {
 return formatTime(new Date); 
}

const fromNowString = function (time) {
	var now = new Date().getTime();
	return timeLengthString(now - time);
}

const timeLengthString = function(time) {
	var t = (time) / 1000;
	var ret = "";
	if (t > 86400) { // 1天
		var a = Math.round(t / 86400);
		ret = a + '天';
	} else if (t > 3600) { // 1小时
		var a = Math.round(t / 3600);
		ret = a + '小时';
	} else if (t > 60) { // 1分钟
		var a = Math.round(t / 60);
		ret = a + '分钟';
	} else {
		ret = Math.round(t) + '秒';
	}
	return ret;
}

const asyncResult = function(ret) {
	return new Promise(function (resolve, reject) {
		resolve(ret);
	});
}

const request = function (url, data = {}, method = "GET") {
	let header = null;
	if (data != null) {
		if (method == 'POST' || method == 'PUTH' || method == 'PATCH')
			header = {
				'Content-Type': 'application/json',
				//'X-Litemall-Token': wx.getStorageSync('token')
			};
	}
	return new Promise(function (resolve, reject) {
		wx.request({
			url: url,
			data: data,
			method: method,
			header: header,
			success: function (res) {
				if (res.statusCode == 200) {
					if (res.data.status == 'success') {
						resolve(res.data);
					} else {
						reject(res.data);
					}
				} else {
					reject(res.data);
				}
			},
			fail: function (err) {
				reject({
					status: 'failure',
					message: err.errMsg,
					data: err
				})
			}
		})
	});
}

const uuid = function() {
		function S4() {
			return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
		}
		return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

const MyLog = {
	log : function(str) {
		console.log(str);
		var logs = wx.getStorageSync('logs') || []
		logs.unshift(nowTimeString() + " " + str)
		if (logs.length > 50) {
			logs = logs.slice(logs.length - 40);
		}
		wx.setStorageSync('logs', logs)
	},
	getLogs : function() {
		return wx.getStorageSync('logs') || []
	},
	cleanLogs: function () {
		wx.setStorageSync('logs', [])
	},
}

module.exports = {
	formatTime: formatTime,
	request: request,
	uuid: uuid,
	nowTimeString: nowTimeString,
	timeLengthString: timeLengthString,
	fromNowString: fromNowString,
	MyLog: MyLog,
	asyncResult: asyncResult,
}
